from django.utils.decorators import method_decorator
from django.utils.deprecation import MiddlewareMixin
from PIL import Image, ImageDraw
import urllib
from hashlib import sha256
import base64
import hmac
from qiniu import Auth
from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View

# 导入models
from myapp.models import *
# 导入序列器
from .myser import *

import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import Image, ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt


# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from mydjango.settings import BASE_DIR

# 导包
from django.db.models import Q, F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

# 导包
import redis
import re

# 定义ip地址和端口
host = '127.0.0.1'
port = 6379

# 定义链接对象
r = redis.Redis(host=host, port=port)


# 插入幻灯片
class InsertPics(APIView):
    def get(self, request):
        # 接收参数
        title = request.GET.get('title')
        link = request.GET.get('link')
        img = request.GET.get('img')

        # 排重
        pics = Pics.objects.filter(title=title).first()

        if pics:
            res = {}
            res['code'] = 405
            res['message'] = '该活动已存在'
            return Response(res)

        # 入库
        pics = Pics(title=title, link=link, image=img)
        pics.save()
        res = {}
        res['code'] = 200
        res['msg'] = '插入幻灯片成功'
        return Response(res)


# 展示幻灯片
class ShowPics(APIView):
    def get(self, request):
        pics = Pics.objects.all()
        if pics:
            pics_ser = PicsSer(pics, many=True).data
            return Response(pics_ser)
        else:
            res = {}
            res['code'] = 405
            res['msg'] = '未添加幻灯片'
            return Response(res)

    # 删除幻灯片
    def delete(self, request):
        # 接收参数
        pid = request.data.get('pid')

        # 查找幻灯片
        pic = Pics.objects.get(id=pid).delete()
        res = {}
        res['code'] = 200
        res['msg'] = '删除成功'
        return Response(res)

    # 修改幻灯片
    def options(self, request):
        # 接收参数
        title = request.data.get('title')
        link = request.data.get('link')
        img = request.data.get('img')
        pid = request.data.get('pid')

        # 查找幻灯片
        pic = Pics.objects.get(id=pid)
        pic.title = title
        pic.link = link
        pic.image = img
        pic.save()

        res = {}
        res['code'] = 200
        res['msg'] = '修改成功'
        return Response(res)
